<template>
	<div class="v-editor" ref="vEditor"></div>
	<v-plus v-model="plusVisible" @on-success="onUploadSuccess"></v-plus>
</template>

<script setup>
import vPlus from "../upload/components/plus.vue"

const props = defineProps({
	modelValue: {
		type: [String, Number],
	},
	disabled: {
		type: Boolean,
		default: false,
	},
})
const emits = defineEmits(["update:modelValue"])

const value = computed({
	get() {
		return props.modelValue
	},
	set(val) {
		emits("update:modelValue", val)
	},
})
const plusVisible = shallowRef(false)

let editor = null
let isReady = false
let isLoading = false
const vEditor = ref(null)

function onUploadSuccess(value) {
	let html = ""
	value.forEach(item => {
		html += `<img src="${item.url}" alt="${item.url.split("/").pop()}"/>`
	})
	editor.insertHtml(html)
}

onMounted(createEditor)
onActivated(createEditor)
onDeactivated(() => {
	if (editor) {
		editor.destroy()
		editor = null
		isReady = false
	}
})

function createEditor() {
	if (isLoading) return
	isLoading = true
	if (vEditor.value) {
		if (!editor) {
			editor = window.CKEDITOR.replace(vEditor.value)
			editor.open_dialog = () => {
				plusVisible.value = true
			}
			editor.on("change", evt => {
				value.value = evt.editor.getData()
			})
			editor.on("instanceReady", evt => {
				isReady = true
				editor.setData(props.modelValue)
				editor.setReadOnly(props.disabled)
			})
		}
	}
	isLoading = false
}

watch(
	() => props.modelValue,
	val => {
		if (editor && isReady) {
			if (val != editor.getData()) {
				editor.setData(val)
			}
		}
	}
)
watch(
	() => props.disabled,
	disabled => {
		if (!editor || !isReady) {
			return
		}
		editor.setReadOnly(disabled)
	}
)

function getData() {
	if (editor && isReady) {
		return editor.getData()
	}
	return null
}
function getText() {
	if (editor && isReady) {
		return editor.document.getBody().getText()
	}
	return null
}

defineExpose({
	getData,
	getText,
})
</script>

<style lang="scss" scoped></style>
